﻿<div class="themeswitcher-container @(Shown ? "themeswitcher-container-shown" : "")">
    @if (Shown && _canRender)
    {
        <DxScrollView id="themesMenu" CssClass="card shadow">
            <div class="list-group list-group-flush">
                @foreach (var themeSet in DemoService.ThemeSets)
                {
                    <span class="card-header list-group-item">@themeSet.Title</span>
                    @foreach (var theme in themeSet.Themes)
                    {
                        <ThemeSwitcherItem @key=@theme.RenderKey Theme="@theme" Apply="@OnApply"/>
                    }
                }
            </div>
        </DxScrollView>
    }
</div>
@code {
    [Parameter] public bool Shown { get; set; }
    [Parameter] public EventCallback<bool> ShownChanged { get; set; }
    [Parameter] public string ThemeName { get; set; }
    [Parameter] public EventCallback<string> ThemeNameChanged { get; set; }

    [Inject] IDocumentMetadataService DocumentMetadataService { get; set; }
    [Inject] DemoService DemoService { get; set; }

    bool _canRender;
    async Task OnApply(ThemeAttributes theme) {
        if (DemoService.CurrentTheme != theme.Name)
        {
            DemoService.CurrentTheme = theme.Name;
            DocumentMetadataService.Update((m) => {
                m.StyleSheet("currentTheme", theme.ResourceUrl);
            });

            ThemeName = theme.Name;
            await ThemeNameChanged.InvokeAsync(ThemeName);
            await ToggleThemeSwitcherPanel(false);
        }
    }

    async Task ToggleThemeSwitcherPanel(bool shown)
    {
        if (shown != Shown)
        {
            Shown = shown;
            await ShownChanged.InvokeAsync(shown);
        }
    }

    protected override void OnAfterRender(bool firstRender)
    {
        _canRender = true;
        if (firstRender && Shown)
            StateHasChanged();
    }

}
